package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zwy.gradetrack.entity.UserRole;
import org.zwy.gradetrack.entity.User;
import org.zwy.gradetrack.entity.Role;
import org.zwy.gradetrack.mapper.UserRoleMapper;
import org.zwy.gradetrack.service.UserRoleService;
import org.zwy.gradetrack.service.UserService;
import org.zwy.gradetrack.service.RoleService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色服务实现类
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    private final UserService userService;

    @Autowired
    public UserRoleServiceImpl(@Lazy UserService userService) {
        this.userService = userService;
    }

    @Autowired
    private RoleService roleService;

    @Override
    public Page<UserRole> pageUserRoles(Integer current, Integer size, Long userId, Long roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, UserRole::getUserId, userId)
                .eq(roleId != null, UserRole::getRoleId, roleId)
                .orderByDesc(UserRole::getCreateTime);
        
        return page(new Page<>(current, size), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRoles(Long userId, List<Long> roleIds) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查角色是否都存在
        List<Role> roles = roleService.listByIds(roleIds);
        if (roles.size() != roleIds.size()) {
            throw new RuntimeException("存在无效的角色ID");
        }

        // 获取用户当前角色
        List<UserRole> existingUserRoles = getUserRoles(userId);
        List<Long> existingRoleIds = existingUserRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());

        // 过滤出需要新增的角色
        List<Long> newRoleIds = roleIds.stream()
                .filter(roleId -> !existingRoleIds.contains(roleId))
                .collect(Collectors.toList());

        if (!newRoleIds.isEmpty()) {
            // 创建新的用户角色关联
            List<UserRole> newUserRoles = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();
            for (Long roleId : newRoleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRole.setCreateTime(now);
                userRole.setUpdateTime(now);
                newUserRoles.add(userRole);
            }
            saveBatch(newUserRoles);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeRoles(Long userId, List<Long> roleIds) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 删除指定的用户角色关联
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId)
                .in(UserRole::getRoleId, roleIds);
        return remove(wrapper);
    }

    @Override
    public List<UserRole> getUserRoles(Long userId) {
        return this.lambdaQuery()
                .eq(UserRole::getUserId, userId)
                .list();
    }

    @Override
    public List<UserRole> getRoleUsers(Long roleId) {
        return this.lambdaQuery()
                .eq(UserRole::getRoleId, roleId)
                .list();
    }

    @Override
    public boolean hasRole(Long userId, Long roleId) {
        return this.lambdaQuery()
                .eq(UserRole::getUserId, userId)
                .eq(UserRole::getRoleId, roleId)
                .count() > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchImport(List<UserRole> userRoles) {
        if (userRoles == null || userRoles.isEmpty()) {
            throw new RuntimeException("导入数据不能为空");
        }

        // 检查所有用户和角色是否存在
        Set<Long> userIds = userRoles.stream()
                .map(UserRole::getUserId)
                .collect(Collectors.toSet());
        Set<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toSet());

        List<User> users = userService.listByIds(userIds);
        if (users.size() != userIds.size()) {
            throw new RuntimeException("存在无效的用户ID");
        }

        List<Role> roles = roleService.listByIds(roleIds);
        if (roles.size() != roleIds.size()) {
            throw new RuntimeException("存在无效的角色ID");
        }

        // 检查是否存在重复的用户角色关联
        for (UserRole userRole : userRoles) {
            if (hasRole(userRole.getUserId(), userRole.getRoleId())) {
                throw new RuntimeException(
                    String.format("用户ID %d 的角色ID %d 已存在",
                        userRole.getUserId(), userRole.getRoleId())
                );
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        userRoles.forEach(userRole -> {
            userRole.setCreateTime(now);
            userRole.setUpdateTime(now);
        });

        // 批量保存
        saveBatch(userRoles);
    }
} 